//
//  ShowProViewController.m
//  LiWuShuo
//
//  Created by 袁小航 on 14/11/13.
//  Copyright (c) 2014年 lanou3g.com 蓝鸥科技. All rights reserved.
//

#import "ShowProViewController.h"
#import "Product.h"
#import "TypeProModel.h"
#import "ProductCollectionViewCell.h"
#import <UIImageView+AFNetworking.h>
#import "Define.h"
#import "ProDetailViewController.h"
#import "AppDelegate.h"
#import "Collect.h"
#import "MJRefresh.h"

@interface ShowProViewController ()<UICollectionViewDelegate, UICollectionViewDataSource>

@property(nonatomic, retain) Product * productView;
@property(nonatomic, retain) NSArray *subProducts;
@property(nonatomic, retain) NSMutableArray *subPHProducts;

//实现收藏
//定义NSManagedObjectContext类型对象
@property(nonatomic, strong) NSManagedObjectContext *managedObjectContext;
//coreData中的数据
@property(nonatomic, retain) NSArray *DBData;
//不论成功与否 收藏后都弹出的alert
@property(nonatomic, retain) UIAlertView *CollAlert;
@property(nonatomic, retain) UIAlertView *CollFailAlert;

//定义一个TypeProModel类型的对象  用来存储“专题”类型的数据
@property(nonatomic, retain) TypeProModel *typeTopicModel;
@property(nonatomic, retain) TypeProModel *typePHModel;

//定义一个nsinteger变量来保存刷新数据的页数
@property(nonatomic, assign) NSInteger page;

@end

@implementation ShowProViewController

- (void)viewWillAppear:(BOOL)animated
{
    self.navigationController.navigationBar.hidden = NO;
    self.tabBarController.tabBar.hidden = NO;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
//    将上一页传过来的Title现实在navigation上
    UILabel * allTopic = [[UILabel alloc]init];
    allTopic.text = _subTitle;
    allTopic.textColor = [UIColor whiteColor];
    allTopic.font = [UIFont systemFontOfSize:16];
    allTopic.frame = CGRectMake(0, 0, 40, 30);
    self.navigationItem.titleView = allTopic;
    
    
    AppDelegate *delegate = [UIApplication sharedApplication].delegate;
    self.managedObjectContext = delegate.managedObjectContext;
    
//    获取数据
//    [self getProductData:0];
    
    
//    创建proCollectionView
    [self createProCollectionView];
    
    [self setupRefresh];
    
//    创建自定义返回按钮
    [self createBackButton];
}

#pragma mark - 刷新
- (void)setupRefresh
{
    _page = 0;
    [_productView.proCollectionView addHeaderWithTarget:self action:@selector(headerRefresh)];
    [_productView.proCollectionView headerBeginRefreshing];
    
    if (![_subType isEqualToString:@"Topic"]) {
        [_productView.proCollectionView addFooterWithTarget:self action:@selector(footerRefresh)];
        [_productView.proCollectionView footerEndRefreshing];
    }
}

- (void)headerRefresh
{
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//        获取数据
        [self getProductData:_page];
        
//        结束刷新
        [_productView.proCollectionView headerEndRefreshing];
    });
}
- (void)footerRefresh
{
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 *NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        _page = _page + 12;
//        获取数据
        [self getProductData:_page];
        
//        结束刷新
        [_productView.proCollectionView footerEndRefreshing];
    });
}

#pragma mark - 创建自定义返回按钮
- (void)createBackButton
{
    UIButton *back = [UIButton buttonWithType:UIButtonTypeCustom];
    back.frame = CGRectMake(0, 0, 25, 25);
    [back setBackgroundImage:[UIImage imageNamed:@"back.png"] forState:UIControlStateNormal];
    [back addTarget:self action:@selector(backPageAction:) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem *backItem = [[UIBarButtonItem alloc]initWithCustomView:back];
    self.navigationItem.leftBarButtonItem = backItem;
}
#pragma mark - 自定义的返回按钮的 响应方法
- (void)backPageAction:(id)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - 获取数据
- (void)getProductData:(NSInteger)page
{
    if ([_subType isEqualToString:@"Topic"]) {
        NSURLSessionDataTask *typeSub = [TypeProModel typeProductWithBlock:^(NSArray *posts, NSError *error) {
            _subProducts = posts;
            [_productView.proCollectionView reloadData];
        } subId:_subID];
    } else if ([_subType isEqualToString:@"Person"] || [_subType isEqualToString:@"Hobby"]) {
        NSURLSessionDataTask *typeSubPH = [TypeProModel typePHProductWithBlock:^(NSArray *posts, NSError *error) {
//            判断page数  如果不是0   就将posts加到原来的数组后面
            if (_page == 0) {
                _subPHProducts = [NSMutableArray arrayWithArray:posts];
                [_productView.proCollectionView reloadData];
            } else {
                [_subPHProducts addObjectsFromArray:posts];
                [_productView.proCollectionView reloadData];
            }
        } subId:_subID page:_page];
    }
}

#pragma mark -
#pragma mark 创建proCollectionView
- (void)createProCollectionView
{
    self.productView = [[Product alloc]initWithFrame:CGRectMake(0, 0, MAIN_SCREEN_WIDTH, MAIN_SCREEN_HEIGHT - 64)];
    
    _productView.proCollectionView.delegate = self;
    _productView.proCollectionView.dataSource = self;
    
    [_productView.proCollectionView registerClass:[ProductCollectionViewCell class] forCellWithReuseIdentifier:@"proCell"];
    
    [self.view addSubview:_productView];
}

#pragma mark -
#pragma mark CollectionView必须实现的方法
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    if ([_subType isEqualToString:@"Topic"]) {
        if (_subProducts.count != 0) {
            return _subProducts.count;
        } else {
            return 10;
        }
    } else {
        if (_subPHProducts.count != 0) {
            return _subPHProducts.count;
        } else {
            return 10;
        }
    }
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    ProductCollectionViewCell *proCell = [collectionView dequeueReusableCellWithReuseIdentifier:@"proCell" forIndexPath:indexPath];
    if ([_subType isEqualToString:@"Topic"]) {
        [proCell.proImage setImageWithURL:[NSURL URLWithString:[_subProducts[indexPath.row] typeImageUrl]] placeholderImage:[UIImage imageNamed:@"placehold.png"]];
        proCell.layer.cornerRadius = 5;
        proCell.layer.masksToBounds = YES;
        proCell.proImage.contentMode = UIViewContentModeScaleAspectFill;
        
        proCell.proInfo.text = [_subProducts[indexPath.row] typeInfo];
        
        proCell.collectButton.collectNum.text = [_subProducts[indexPath.row] typeCollectNum];
//        添加点击收藏按钮的事件
        proCell.collectButton.tag = indexPath.row + 1000;
        [proCell.collectButton addTarget:self action:@selector(collectButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    } else if ([_subType isEqualToString:@"Person"] || [_subType isEqualToString:@"Hobby"]) {
        [proCell.proImage setImageWithURL:[NSURL URLWithString:[_subPHProducts[indexPath.row] typeImageUrl]] placeholderImage:[UIImage imageNamed:@"placehold.png"]];
        proCell.layer.cornerRadius = 5;
        proCell.layer.masksToBounds = YES;
        proCell.proImage.contentMode = UIViewContentModeScaleAspectFill;
        proCell.proInfo.text = [_subPHProducts[indexPath.row] typeInfo];
        
        proCell.collectButton.collectNum.text = [_subPHProducts[indexPath.row] typeCollectNum];
//        添加点击收藏按钮的事件
        proCell.collectButton.tag = indexPath.row + 1000;
        [proCell.collectButton addTarget:self action:@selector(collectButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    } else {
        if (_subPHProducts.count == 0 || _subPHProducts.count == 0) {
            UIAlertView *netError = [[UIAlertView alloc]initWithTitle:@"网络连接" message:@"网络异常，请重试..." delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
            [netError show];
        }
    }
    
    return proCell;
}

#pragma mark -
#pragma mark - collectButton的响应事件
- (void)collectButtonAction:(UIButton *)sender
{
    //    通过butotn的tag值 获取到数组中所需要的数据
    if ([_subType isEqualToString:@"Topic"]) {
        UIButton *topicButton = sender;
        self.typeTopicModel = _subProducts[topicButton.tag - 1000];
    } else if ([_subType isEqualToString:@"Person"] || [_subType isEqualToString:@"Hobby"]) {
        UIButton *PHButton = sender;
        self.typePHModel = _subPHProducts[PHButton.tag - 1000];
    }
    
    //    获取coredata中所有数据
    [self selectDataFromCoredata];
    
    for (Collect *coll in _DBData) {
        if ([coll.info isEqualToString:_typeTopicModel.typeInfo] || [coll.info isEqualToString:_typePHModel.typeInfo]) {
            //            当收藏失败的时候  弹出提示框
            self.CollFailAlert = [[UIAlertView alloc]initWithTitle:@"" message:@"已取消收藏该礼物！" delegate:self cancelButtonTitle:nil otherButtonTitles:nil];
            [_CollFailAlert show];
            //            提示框1秒后自动消失
            [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerAction) userInfo:nil repeats:NO];
            
            //            发现与数据库中的数据相同
            NSFetchRequest *request = [[NSFetchRequest alloc]initWithEntityName:@"Collect"];
            //            查出该数据
            if ([_subType isEqualToString:@"Topic"]) {
                request.predicate = [NSPredicate predicateWithFormat:[NSString stringWithFormat:@"info = '%@'", _typeTopicModel.typeInfo]];
            } else if ([_subType isEqualToString:@"Person"] || [_subType isEqualToString:@"Hobby"]) {
                request.predicate = [NSPredicate predicateWithFormat:[NSString stringWithFormat:@"info = '%@'", _typePHModel.typeInfo]];
            }
            //            将该数据保存到临时数组中
            NSArray *temp = [self.managedObjectContext executeFetchRequest:request error:nil];
            //            定义一个新的Collect类型的对象  用来保存查到的数据
            Collect *tempColl = temp[0];
            //            从数据库中删除该元素
            if (tempColl != nil) {
                [self.managedObjectContext deleteObject:tempColl];
                [self.managedObjectContext save:nil];
            }
            return;
        }
    }
    //    添加到数据库
    NSEntityDescription *collEntity = [NSEntityDescription entityForName:@"Collect" inManagedObjectContext:self.managedObjectContext];
    //    创建Collect 对象
    Collect *coll = [[Collect alloc]initWithEntity:collEntity insertIntoManagedObjectContext:self.managedObjectContext];
    
    //    对Collect对象赋值
    if ([_subType isEqualToString:@"Topic"]) {
        coll.info = _typeTopicModel.typeInfo;
        coll.image = _typeTopicModel.typeImageUrl;
        coll.url = _typeTopicModel.typeUrl;
    } else if ([_subType isEqualToString:@"Person"] || [_subType isEqualToString:@"Hobby"]) {
        coll.info = _typePHModel.typeInfo;
        coll.image = _typePHModel.typeImageUrl;
        coll.url = _typePHModel.typeUrl;
    }
    
    //    保存到数据库
    [self.managedObjectContext save:nil];
    
    //    显示“收藏成功”
    self.CollAlert = [[UIAlertView alloc]initWithTitle:@"" message:@"收藏成功!" delegate:self cancelButtonTitle:nil otherButtonTitles:nil];
    [_CollAlert show];
    [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerAction) userInfo:nil repeats:NO];
    
}
#pragma mark - 一秒之后 “收藏成功”消失
- (void)timerAction
{
    [_CollFailAlert dismissWithClickedButtonIndex:0 animated:YES];
    [_CollAlert dismissWithClickedButtonIndex:0 animated:YES];
}

#pragma mark - 获取数据库中的持久化数据
- (void)selectDataFromCoredata
{
    //    获取coredata中所有的数据
    NSFetchRequest *request = [[NSFetchRequest alloc]initWithEntityName:@"Collect"];
    self.DBData = [self.managedObjectContext executeFetchRequest:request error:nil];
    
}



#pragma mark - 点击item的响应
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    if ([_subType isEqualToString:@"Topic"]) {
        ProDetailViewController *detailVC = [[ProDetailViewController alloc]init];
        if (_subProducts.count != 0) {
            detailVC.proDetailImage = [_subProducts[indexPath.row] typeImageUrl];
            detailVC.proDetailInfo = [_subProducts[indexPath.row] typeInfo];
            detailVC.proDetailUrl = [_subProducts[indexPath.row] typeUrl];
        }
        [self.navigationController pushViewController:detailVC animated:YES];
    } else {
        ProDetailViewController *detailPHVC = [[ProDetailViewController alloc]init];
        if (_subPHProducts.count != 0) {
            detailPHVC.proDetailImage = [_subPHProducts[indexPath.row] typeImageUrl];
            detailPHVC.proDetailInfo = [_subPHProducts[indexPath.row] typeInfo];
            detailPHVC.proDetailUrl = [_subPHProducts[indexPath.row] typeUrl];
        }
        [self.navigationController pushViewController:detailPHVC animated:YES];
    }
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
